package com.xiaomi.filter;

import com.xiaomi.entity.User;
import com.xiaomi.service.UserService;
import com.xiaomi.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TODO
 *
 * @author jy
 * @date 2021/5/24
 */
@WebFilter("/login.jsp")
public class LoginFilter implements Filter {

    private final UserService userService = new UserServiceImpl();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //没有getCookies 强转
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取所有cookies
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //如果cookie中存在on,判断其中值是否能查询到用户
                if ("on".equals(cookie.getName())) {
                    String value = cookie.getValue();
                    String[] split = value.split(":");
                    String username = split[0];
                    String password = split[1];
                    //能查询出,则转发到首页
                    User user = userService.login(username, password);
                    if (user != null) {
                        //浏览器关闭后 session就消失了 补充用户对象到session才能看到头部的用户名
                        req.getSession().setAttribute("loginUser", user);
                        req.getRequestDispatcher("index.jsp").forward(req, resp);
                        break;
                    }
                }
            }
        }
        filterChain.doFilter(req, resp);
    }
}
